package br.pucrs.lognplay.faces.bean;

import java.util.List;
import java.util.UUID;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import br.pucrs.lognplay.entity.Client;
import br.pucrs.lognplay.entity.LogSource;
import br.pucrs.lognplay.entity.User.Role;
import br.pucrs.lognplay.service.ClientManagementService;
import br.pucrs.lognplay.service.LogSourceManagementService;

@ManagedBean
@ViewScoped
public class LogSourceManagementBean extends Bean {

	private LogSource logSource;

	private List<Client> clients;

	@EJB
	private LogSourceManagementService logSourceManagementService;

	@EJB
	private ClientManagementService clientManagementService;

	public LogSource getLogSource() {
		try {
			if (logSource == null) {
				String logSourceId = getParameterValue("logSourceId");

				if (logSourceId == null) {
					Role loggedUserRole = getLoggedUser().getRole();

					if (loggedUserRole.equals(Role.MASTER_USER)) {
						logSource = new LogSource(UUID.randomUUID());
					} else if (loggedUserRole.equals(Role.CLIENT_MASTER_USER)) {
						logSource = new LogSource(UUID.randomUUID());
						logSource.setClient(getLoggedUser().getClient());
					}
				} else {
					logSource = logSourceManagementService.getLogSourceById(logSourceId);
				}
			}

			return logSource;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}

	public void setLogSource(LogSource logSource) {
		this.logSource = logSource;
	}

	public boolean isClientRendered() {
		Role loggedUserRole = getLoggedUser().getRole();

		if (loggedUserRole.equals(Role.MASTER_USER)) {
			return true;
		} else {
			return false;
		}
	}

	public List<Client> getClients() {
		try {
			if (clients == null) {
				clients = clientManagementService.listAllClients();
			}

			return clients;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}

	public String getLogSourceConfiguration() {
		String id = logSource.getId();
		String externalId = id.replace("-", "");

		return ":app-name, isequal, \"" + externalId + "\" @@LognplayELB-859008916.sa-east-1.elb.amazonaws.com:10514;RSYSLOG_ForwardFormat";
	}

	public String save() {
		try {
			logSourceManagementService.mergeLogSource(logSource);
			addInformationMessage("The changes have been saved", null);
			return null;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}
}
